package com.boarsoft.boar.gateway.demo;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.springframework.beans.factory.annotation.Autowired;

import com.boarsoft.flow.core.bean.ProcessHandler;

/**
 * 使用时需申明此Bean的实例，注入group，再配置到流程中
 * 
 * @author Mac_J
 *
 */
// @Component("dubboServiceProxy")
public class DubboServiceProxy implements ProcessHandler {
	@Autowired
	protected ApplicationConfig applicationConfig;
	@Autowired
	protected RegistryConfig registryConfig;
	@Autowired
	protected ApplicationConfig application;

	@Autowired
	protected RegistryConfig registry;

	protected String interfaceName;

	protected Class<?> interfaceClass;

	protected String group;
	
	protected String version;

	@Override
	public Object process(String entry, Object data, Throwable throwable) throws Throwable {
		// RpcContext.getContext().setAttachment(Constants.REQUEST_TAG_KEY,"tag1");
		// try {
		// target = this.getInvokeService(interfaceClass, "0");
		// return target.process(entry, data, throwable);
		ProcessHandler ph = this.getInvokeService(ProcessHandler.class, "0");
		return ph.process(entry, data, throwable);
		// } finally {
		// RpcContext.getContext()
		// }
	}

	public <T> T getInvokeService(Class<T> interfaceClass, String tag) {
		ReferenceConfig<T> rc = new ReferenceConfig<T>();
		rc.setApplication(application);
		rc.setRegistry(registry);
		rc.setGroup(group);
		rc.setVersion(version);
		rc.setTag(tag);
		// rc.setInterface(ProcessHandler.class);
		rc.setInterface(interfaceClass);
		ReferenceConfigCache cache = ReferenceConfigCache.getCache();
		return cache.get(rc);
	}

	public void setInterfaceName(String interfaceName) throws ClassNotFoundException {
		this.interfaceName = interfaceName;
		this.interfaceClass = Class.forName(interfaceName);
	}

	// public ProcessHandler getTarget() {
	// return target;
	// }
	//
	// public void setTarget(ProcessHandler target) {
	// this.target = target;
	// }

	public String getGroup() {
		return group;
	}

	public void setGroup(String group) {
		this.group = group;
	}

}
